#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time    : 2025/5/9 15:20
@Author  : HZP
@File    : jwt_service.py
"""
from typing import Any

import jwt

from config import Config
from internal.exception.exception import UnauthorizedException


class JwtService:

    @classmethod
    def generate_token(cls, payload: dict[str, Any]) -> str:
        secret_key = Config.JWT_SECRET_KEY
        """生成token"""
        return jwt.encode(payload, secret_key, algorithm="HS256")

    @classmethod
    def parse_token(cls, token: str) -> dict[str, Any]:
        secret_key = Config.JWT_SECRET_KEY
        """解析token"""
        try:
            return jwt.decode(token, secret_key, algorithms=["HS256"])
        except jwt.ExpiredSignatureError:
            raise UnauthorizedException("授权认证凭证已过期请重新登陆")
        except jwt.InvalidTokenError:
            raise UnauthorizedException("解析token出错，请重新登陆")
        except Exception as e:
            raise UnauthorizedException(str(e))